/* jshint esversion: 6 */  //去除es6的警告
//------------------------------------------------旧版XMLHttpRequest----------------------------------------------------------
function gets(url, data, fn) {
    var xhr = new XMLHttpRequest();			       
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            fn.call(this, JSON.parse(xhr.responseText));
        }
    };
    xhr.open('GET', url+'?'+formatParams(data), true);
    xhr.send(null);
}
function posts(url, data, fn) {
    var xhr = new XMLHttpRequest();          
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            fn.call(this, JSON.parse(xhr.responseText));
        }
    };
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(formatParams(data));
}
//------------------------------------------------新版fetch----------------------------------------------------------
function fetchPost(url, data) {			
    var obj = {
        method: 'POST',
        headers: { //这里有s,傻傻分不清楚
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formatParams(data)
    };
    return new Promise((resolve, reject) => {
        fetch(url, obj).then(res => {
            resolve(res.json());
        }).catch(error => {
            reject(error);
        });
    });
}

function fetchGet(url) {			
    return new Promise((resolve, reject) => {
        fetch(url).then(res => {
            if (res.ok) {
                resolve(res.json());						
            }
        }).catch(error => {
            reject(error);
        });
    });
}
//相当于 qs.stringify()
function formatParams(obj) {
    var arr = [];
    for (var name in obj) {
        arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(obj[name]));				
    }
    return arr.join('&');
}

